/*
 *英才会硕信息科技有限公司拥有本软件的版权，拥有本软件版权2025   并保留所有权利。
 *Copyright 2021,YCHS Information&Science Technology Co.,Ltd,
 *All rights reserved.
 */
package com.ychs.lawyerback01.controller;

import com.ychs.lawyerback01.annotation.RequirePermission;
import com.ychs.lawyerback01.common.R;
import com.ychs.lawyerback01.common.ResultCode;
import com.ychs.lawyerback01.service.PrivilegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xuehongjin
 * @version 1.0
 * @date 2025/8/22
 */
@RestController
@RequestMapping("/api/privilege")
public class PrivilegeController {

    @Autowired
    private PrivilegeService privilegeService;


    @GetMapping("/getByRoleId/{roleId}")
    @RequirePermission("system:role:getByRoleId")
    public R getByRoleId(@PathVariable Long roleId) {
        List<Long> menuIds = privilegeService.getMenuIdsByRoleId(roleId);
        return R.success(menuIds);
    }


    @PostMapping("/save")
    @RequirePermission("system:role:save")
    public R save(@RequestBody Map<String, Object> params) {
        // 1. 处理roleId：先判空，再转换（避免NullPointerException）
        Object roleIdObj = params.get("roleId");
        if (roleIdObj == null) {
            return R.fail(ResultCode.DOCUMENT_NOT_FOUND);// 提前返回错误，避免后续异常
        }
        Long roleId = Long.parseLong(roleIdObj.toString());

        // 2. 处理menuIds：先按List<Integer>接收，再转为List<Long>
        Object menuIdsObj = params.get("menuIds");
        if (menuIdsObj == null || !(menuIdsObj instanceof List)) {
            return R.fail();
        }
        // 先转为List<Integer>（注意：需确保集合元素是Integer，避免ClassCastException）
        List<Integer> menuIdsInteger = (List<Integer>) menuIdsObj;
        // 数值转换：将Integer转为Long（核心修复点）
        List<Long> menuIds = menuIdsInteger.stream()
                .map(Integer::longValue) // 或 Long::valueOf
                .collect(Collectors.toList());

        // 3. 调用Service
        privilegeService.saveRolePermissions(roleId, menuIds);
        return R.success("权限保存成功");
    }
}
